#!/usr/bin/env node
'use strict'

require('./util/prototype.js')
const fileUtil = require('./util/fileUtil')

const cheerio = require('cheerio')
const date = new Date().format('yyyy-MM-dd-S')

const processData = array => {
  let rowLength = array.length

  let colLength = array
    .map(item => {
      item.length
    })
    .max()

  //补齐列
  for (let i = 0; i < rowLength; i++) {
    if (array[i].length < colLength) {
      for (let j = array[i].length; j < colLength; j++) {
        array[i].push('')
      }
    }
  }

  //去除undefind
  for (let i = 0; i < rowLength; i++) {
    for (let j = 0; j < colLength; j++) {
      if (typeof array[i][j] == 'undefined') {
        array[i][j] = ''
      }
    }
  }

  let hasDel = false
  //删除空列
  let delCols = []
  for (let i = 0; i < colLength; i++) {
    if (array[0][i] == '') {
      let del = true
      for (let j = 0; j < rowLength; j++) {
        del = del && array[j][i] == ''
        hasDel = hasDel || del
      }
      if (del) {
        delCols.push(i)
      }
    }
  }

  if (hasDel) {
    array = array.map(row => {
      let newRow = []
      newRow = row.filter((value, index) => {
        return !delCols.contains(index)
      })
      return newRow
    })
  }

  return array
}

module.exports = function(workFolder, htmlEncoding) {
  fileUtil
    .readDirPromise(
      workFolder,
      file =>
        (file.endsWith('.html') || file.endsWith('.htm')) &&
        !file.startsWith('_')
    )
    .then(files => {
      files.map(file => {
        var filePath = `${workFolder}/${file}`

        var data = []
        var index = 1

        fileUtil
          .readFilePromise(filePath, htmlEncoding)
          .then(html => {
            var _html = ''
            var $ = cheerio.load(html, {
              decodeEntities: false
            })
            $('table').each(function() {
              var item = {
                name: `sheet${index}`,
                data: []
              }

              $(this)
                .find('tr,td,p,span')
                .removeAttr('style')
                .removeAttr('class')
                .removeAttr('align')
                .removeAttr('valign')
                .removeAttr('width')
                .removeAttr('rowspan')
                .removeAttr('colspan')

              $(this)
                .find('p')
                .each(function() {
                  var text = $(this).text()
                  $(this).html(text.trim())
                })

              $(this)
                .find('tr')
                .each(function() {
                  var text = $(this)
                    .text()
                    .trim()
                  if (text == '') {
                    $(this).remove()
                  }
                })

              $(this)
                .find('tr')
                .each(function() {
                  var row = []

                  $(this)
                    .find('td')
                    .each(function() {
                      var text = $(this)
                        .text()
                        .trim()
                      row.push(text)
                    })

                  item.data.push(row)
                })

              item.data = processData(item.data)

              data.push(item)
              index += 1

              var tbody = $(this).html()
              _html += `<table border="1">${tbody}</table>`
            })
            _html =
              `<style>
            table { width: 900px; min-height: 50px; line-height: 50px; text-align: center; border-color:#b6ff00; border-collapse: collapse;}
            </style>` + _html.replace(/<\/{0,1}p>/g, '')

            return _html
          })
          .then(html => {
            // writeFilePromise(html, `${workFolder}_${file}`, 'gbk').then(filePath => {
            //     console.log(`${filePath}已保存`)
            // })

            var excelFile = file.replace('.html', '.xls')
            excelFile = excelFile.replace('.htm', '.xls')
            fileUtil
              .writeExcelPromise(data, `${workFolder}/_${date}_${excelFile}`)
              .then(filePath => {
                console.log(`${filePath}已保存`)
              })
            //var buffer = xlsx.build(data);
          })
      })
    })
}
